package com.system.healthproject.model.admin.service.impl;

import com.system.healthproject.bean.PagesBean;
import com.system.healthproject.common.ApiResult;
import com.system.healthproject.mapper.*;
import com.system.healthproject.model.admin.paramsbean.*;
import com.system.healthproject.model.admin.service.AdminPatientService;
import com.system.healthproject.pojo.*;
import com.system.healthproject.service.RoleService;
import com.system.healthproject.utils.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class AdminPatientServiceImp implements AdminPatientService {

    @Autowired
    PatientMapper patientMapper;
    @Autowired
    LoginMapper mapper;
    @Autowired
    RoleService roleService;
    @Autowired
    RecordMapper recordMapper;
    @Autowired
    NowHistoryMapper nowHistoryMapper;
    @Autowired
    BeforeHistoryMapper beforeHistoryMapper;
    @Autowired
    FamilyHistoryMapper familyHistoryMapper;
    @Autowired
    AccountMapper accountMapper;
    @Autowired
    SymptomMapper symptomMapper;
    @Autowired
    DiseaseOnsetMapper diseaseOnsetMapper;
    @Autowired
    AbnormalEEGMapper abnormalEEGMapper;
    @Autowired
    CtMapper ctMapper;
    @Autowired
    DrugMapper drugMapper;
    @Autowired
    OperationMapper operationMapper;
    @Autowired
    ChronicMapper chronicMapper;
    @Autowired
    InheritanceMapper inheritanceMapper;


    /**
     * 后端添加患者
     * @param patientDoctor
     * @return
     */
    @Transactional
    @Override
    public boolean addPatient(AddPatientParams patientDoctor) {
        Patient record = new Patient();
        record.setPatientNick(patientDoctor.getPatientNick());
        record.setPatientSex(patientDoctor.getPatientSex());
        record.setPatientBirthday(patientDoctor.getPatientBirthday());
        record.setIllage(patientDoctor.getIllage());
        record.setProvince(patientDoctor.getProvince());
        record.setCity(patientDoctor.getCity());
        patientMapper.insertSelective(record);
        Integer patientId = record.getPatientId();
        Login record1 = new Login();
        record1.setLoginPhone(patientDoctor.getLoginPhone());
        record1.setLoginPassword(Md5Utils.md5("123456"));
        record1.setLoginPatientid(patientId);
        record1.setCreatetime(new Date());
        record1.setLoginState(1);
        record1.setLoginHeadimg("http://img1.imgtn.bdimg.com/it/u=1728577482,2585850803&fm=26&gp=0.jpg");
        mapper.insert(record1);
        Integer loginId = record1.getLoginId();
        Boolean aBoolean = roleService.addUserRole(loginId, 4);
        Account record2 = new Account();
        record2.setLoginId(loginId);
        record2.setVirtualmoney(0.0);
        accountMapper.insert(record2);
        return aBoolean;
    }

    @Transactional
    @Override
    public ApiResult addRecord(AddRecordParams addRecordParams) {
        NowHistory record1 = new NowHistory();
        Integer isIiagnosis = addRecordParams.getIsIiagnosis();//是否诊断
        record1.setDiagnosisState(isIiagnosis);
        Integer isEEG = addRecordParams.getIsEEG();//是否脑电图
        record1.setEncephlogramState(isEEG);
        Integer isCT = addRecordParams.getIsCT();//是否ct
        record1.setCtState(isCT);
        Integer geneState = addRecordParams.getGeneState();//基因状态
        record1.setGeneState(geneState);
        Integer attacksNumber = addRecordParams.getAttacksNumber();//发作次数
        record1.setAttacksNumber(attacksNumber);
        Integer attacksFrequency = addRecordParams.getAttacksFrequency();//发作频率（1 日 2周 3月）
        record1.setAttacksFrequency(attacksFrequency);
        Integer medicationState = addRecordParams.getMedicationState();//是否药物治疗
        record1.setMedicationState(medicationState);
        Integer operationState = addRecordParams.getOperationState();//是否手术
        record1.setOperationState(operationState);
        Integer hormoneState = addRecordParams.getHormoneState();//是否甲强激素治疗
        record1.setHormoneState(hormoneState);
        Integer immuneState = addRecordParams.getImmuneState();//是否免疫治疗状态
        record1.setImmuneState(immuneState);
        Integer ketogenicState = addRecordParams.getKetogenicState();//是否生酮饮食状态（1 是 2否）
        record1.setKetogenicState(ketogenicState);
        Integer otherState = addRecordParams.getOtherState();
        record1.setOtherState(otherState);
        int insert1 = nowHistoryMapper.insert(record1);
        if(insert1!=1){
            return  ApiResult.failure("添加失败");
        }
        Integer nowhistoryId = record1.getNowhistoryId();
        if(isIiagnosis==1){
            List<Integer> symptomIds = addRecordParams.getSymptomIds();
            List<Integer> diseaseOnsetIds = addRecordParams.getDiseaseOnsetIds();
            if(symptomIds==null||symptomIds.size()==0){
                return ApiResult.failure("诊断症状不能为空");
            }
            if(diseaseOnsetIds==null||diseaseOnsetIds.size()==0){
                return ApiResult.failure("综合症不能为空");
            }
            nowHistoryMapper.addSymptoms(nowhistoryId,symptomIds);
            nowHistoryMapper.addDiseaseOnsets(nowhistoryId,diseaseOnsetIds);
        }
        if(isEEG==2){
            List<Integer> integers = addRecordParams.geteEGIds();
            if(integers==null||integers.size()==0){
                return ApiResult.failure("脑电图不能为空");
            }
            nowHistoryMapper.insertegIds(nowhistoryId,integers);
        }
        if(isCT==2){
            List<Integer> ctIds = addRecordParams.getCtIds();
            if(ctIds==null||ctIds.size()==0){
                return ApiResult.failure("ct异常不能为空");
            }
            nowHistoryMapper.addCtIds(nowhistoryId,ctIds);
        }
        if(medicationState==1){
            List<Integer> drugIds = addRecordParams.getDrugIds();
            if(drugIds==null||drugIds.size()==0){
                return ApiResult.failure("药物治疗药品不能为空");
            }
            nowHistoryMapper.addDrug(nowhistoryId,drugIds);
        }
        if(operationState==1){
            List<Integer> operationIds = addRecordParams.getOperationIds();
            if(operationIds==null||operationIds.size()==0){
                return ApiResult.failure("手术不能为空");
            }
            nowHistoryMapper.addOperation(nowhistoryId,operationIds);
        }
        BeforeHistory record2 = new BeforeHistory();
        Integer drugAllergyState = addRecordParams.getDrugAllergyState();//是否药物过敏
        record2.setDrugallergyState(drugAllergyState);
        Integer traumaState = addRecordParams.getTraumaState();//是否有外伤史
        record2.setTraumaState(traumaState);
        if(traumaState==1){
            String traumaContent = addRecordParams.getTraumaContent();//外伤内容
            record2.setTraumaContent(traumaContent);
        }
        Integer chronicstate = addRecordParams.getChronicstate();//慢病史
        record2.setChronicState(chronicstate);
        Integer injuryState = addRecordParams.getInjuryState();//产伤状态
        record2.setInjuryState(injuryState);
        Integer infectedState = addRecordParams.getInfectedState();//是否感染
        record2.setInfectedState(infectedState);
        Integer hemorrhageState = addRecordParams.getHemorrhageState();//出血
        record2.setHemorrhageState(hemorrhageState);
        Integer convulsionsState = addRecordParams.getConvulsionsState();//是否高热惊厥史（1 是   2 否）
        record2.setConvulsionsState(convulsionsState);
        beforeHistoryMapper.insert(record2);
        Integer beforehistoryId = record2.getBeforehistoryId();
        if(drugAllergyState==1){
            List<Integer> drugAllergyIds = addRecordParams.getDrugAllergyIds();
            if(drugAllergyIds==null||drugAllergyIds.size()==0){
                return ApiResult.failure("过敏药物不能为空");
            }
            beforeHistoryMapper.addDrugAllergy(beforehistoryId,drugAllergyIds);
        }
        if(chronicstate==1){
            List<Integer> chronicIds = addRecordParams.getChronicIds();
            if(chronicIds==null||chronicIds.size()==0){
                return ApiResult.failure("慢病史不能为空");
            }
            beforeHistoryMapper.addChronic(beforehistoryId,chronicIds);
        }
        FamilyHistory record3 = new FamilyHistory();
        Integer inheritanceState = addRecordParams.getInheritanceState();//是否有家族病
        record3.setInheritanceState(inheritanceState);
        Integer marryState = addRecordParams.getMarryState();//是否结婚
        record3.setMarryState(marryState);
        Integer birthState = addRecordParams.getBirthState();//是否生育
        record3.setBirthState(birthState);
        familyHistoryMapper.insert(record3);
        Integer familyhistoryId = record3.getFamilyhistoryId();
        if(inheritanceState==1){
            List<Integer> inheritanceIds = addRecordParams.getInheritanceIds();
            if(inheritanceIds==null||inheritanceIds.size()==0){
                return ApiResult.failure("家族病不能为空");
            }
            familyHistoryMapper.addInheritance(familyhistoryId,inheritanceIds);
        }
        Record record = new Record();
        record.setPatientId(addRecordParams.getPatient_id());
        record.setCreatetime(new Date());
        record.setNowhistoryId(nowhistoryId);
        record.setBeforehistoryId(beforehistoryId);
        record.setFamilyhistoryId(familyhistoryId);
        int insert = recordMapper.insert(record);
        return ApiResult.withBoolean(insert==1,"添加病例成功","添加病例失败");
    }

    @Override
    public PagesBean<PatientParems> getListPatient(Integer page, Integer size,
                                                   String name,
                                                   Integer sex,
                                                   Integer city,
                                                   Integer hasRecord,
                                                   String diagnosis_time,
                                                   Integer doctorId) {
        int frist = (page - 1) * size;
        List<PatientParems> listPatient =
                patientMapper.getListPatient(frist,size,name,sex,city,hasRecord,diagnosis_time,doctorId);
        int listPatientCount =
                patientMapper.getListPatientCount(frist,size,name,sex,city,hasRecord,diagnosis_time,doctorId);
        PagesBean<PatientParems> pagesBean = new PagesBean<PatientParems>();
        pagesBean.setNowsPage(page);
        pagesBean.setPageSize(size);
        pagesBean.setData(listPatient);
        pagesBean.setDataCount(listPatientCount);
        return pagesBean;
    }

    @Override
    public boolean changUserDoctors(PatientDoctor patientDoctor) {
        int patientId = patientMapper.getPatientId(patientDoctor.getPatientId());
        patientDoctor.setPatientId(patientId);
        int i = patientMapper.changUserDoctors(patientDoctor);
        return i==1;
    }

    @Override
    public PatientNumberParams getPatientNumber() {
        int patientTotal = patientMapper.getPatientTotal();
        int nowWeekTotal = patientMapper.getNowWeekTotal();
        PatientNumberParams patientNumberParams = new PatientNumberParams();
        patientNumberParams.setNewAddPatientNumber(nowWeekTotal);
        patientNumberParams.setAllPatientNumber(patientTotal);
        return patientNumberParams;
    }

    @Override
    public PatientNumberParams adminPatientService(Integer provinceCode) {
        int patientTotal = patientMapper.getPatientTotalByCode(provinceCode);
        int nowWeekTotalByCode = patientMapper.getNowWeekTotalByCode(provinceCode);
        PatientNumberParams patientNumberParams = new PatientNumberParams();
        patientNumberParams.setNewAddPatientNumber(nowWeekTotalByCode);
        patientNumberParams.setAllPatientNumber(patientTotal);
        return patientNumberParams;
    }

    @Override
    public List<ProvinceParams> getIsPatientByProvince() {
        List<ProvinceParams> isPatientByProvince = patientMapper.getIsPatientByProvince();
        return isPatientByProvince;
    }

    @Override
    public RecordInfoParams getRecordInfoByUserId(Integer userId) {
        RecordInfoParams recordInfoParams = new RecordInfoParams();
        Record recordInfoByUserId = recordMapper.getRecordInfoByUserId(userId);
        Integer nowhistoryId = recordInfoByUserId.getNowhistoryId();

        NowHistory nowHistory = nowHistoryMapper.selectByPrimaryKey(nowhistoryId);
        Integer diagnosisState = nowHistory.getDiagnosisState();//诊断状态（1 是   2否）
        recordInfoParams.setDiagnosis_state(diagnosisState);
        if(diagnosisState==1){
            List<Symptom> symptoms = symptomMapper.selectListByNowHisId(nowhistoryId);
            recordInfoParams.setSymptoms(symptoms);
            List<DiseaseOnset> diseaseOnsets = diseaseOnsetMapper.selectListByNowHisId(nowhistoryId);
            recordInfoParams.setDiseaseOnsets(diseaseOnsets);
        }
        Integer encephlogramState = nowHistory.getEncephlogramState();//（1 正常  2异常）
        recordInfoParams.setEncephlogram_state(encephlogramState);
        if(encephlogramState==2){
            List<AbnormalEEG> abnormalEEGS = abnormalEEGMapper.selectListByNowHisId(nowhistoryId);
            recordInfoParams.setAbnormalEEGS(abnormalEEGS);
        }
        Integer ctState = nowHistory.getCtState();//核磁/CT状态（1 正常  2异常）
        recordInfoParams.setCt_state(ctState);
        if(ctState==2){
            List<Ct> ctList = ctMapper.selectListByNowHisId(nowhistoryId);
            recordInfoParams.setCts(ctList);
        }
        Integer geneState = nowHistory.getGeneState();//基因状态
        recordInfoParams.setGeneState(geneState);
        Integer attacksNumber = nowHistory.getAttacksNumber();//发作次数
        recordInfoParams.setAttacks_number(attacksNumber);
        Integer attacksFrequency = nowHistory.getAttacksFrequency();
        recordInfoParams.setAttacks_frequency(attacksFrequency);//发作频率（1 日 2周 3月）
        Integer medicationState = nowHistory.getMedicationState();//药物治疗状态（ 1 是 2否）
        recordInfoParams.setMedication_state(medicationState);
        if(medicationState==1){
            List<Drug> drugs = drugMapper.selectListByNowHisId(nowhistoryId);
            recordInfoParams.setMedicationDrugList(drugs);
        }
        Integer operationState = nowHistory.getOperationState();//是否手术状态（1 是 2否）
        recordInfoParams.setOperation_state(operationState);
        if(operationState==1){
            List<Operation> operations = operationMapper.selectListByNowHisId(nowhistoryId);
            recordInfoParams.setOperationsList(operations);
        }
        Integer hormoneState = nowHistory.getHormoneState();//甲强激素治疗状态（1 是  2否）
        recordInfoParams.setHormone_state(hormoneState);
        Integer immuneState = nowHistory.getImmuneState();//免疫治疗状态（1 是 2否）
        recordInfoParams.setImmune_state(immuneState);
        Integer ketogenicState = nowHistory.getKetogenicState();//生酮饮食状态（1 是 2否）
        recordInfoParams.setKetogenic_state(ketogenicState);
        Integer otherState = nowHistory.getOtherState();//现病史其他状态（1 是  2否）
        recordInfoParams.setOther_state(otherState);

        Integer beforehistoryId = recordInfoByUserId.getBeforehistoryId();
        BeforeHistory beforeHistory = beforeHistoryMapper.selectByPrimaryKey(beforehistoryId);
        Integer drugallergyState = beforeHistory.getDrugallergyState();//是否药物过敏（1 是    2 否）
        recordInfoParams.setDrugAllergy_state(drugallergyState);
        if(drugallergyState==1){
            List<Drug> drugs = drugMapper.selectListByBeforeHis(beforehistoryId);
            recordInfoParams.setBeforeDrugList(drugs);
        }
        Integer traumaState = beforeHistory.getTraumaState();//是否有外伤史（1.是   2.否）
        recordInfoParams.setTrauma_state(traumaState);
        if(traumaState==1){
            String traumaContent = beforeHistory.getTraumaContent();
            recordInfoParams.setTrauma_content(traumaContent);
        }
        Integer chronicState = beforeHistory.getChronicState();//慢病史状态（1 是   2 否）
        recordInfoParams.setChronic_state(chronicState);
        if(chronicState==1){
            List<Chronic> chronics = chronicMapper.selectListByBeforeHis(beforehistoryId);
            recordInfoParams.setChronics(chronics);
        }
        Integer injuryState = beforeHistory.getInjuryState();//产伤状态（1 是   2 否）
        recordInfoParams.setInjury_state(injuryState);
        Integer infectedState = beforeHistory.getInfectedState();//是否感染（1 是   2 否）
        recordInfoParams.setInfected_state(infectedState);
        Integer hemorrhageState = beforeHistory.getHemorrhageState();//出血（1 是   2 否）
        recordInfoParams.setHemorrhage_state(hemorrhageState);
        Integer convulsionsState = beforeHistory.getConvulsionsState();//是否高热惊厥史（1 是   2 否）
        recordInfoParams.setConvulsions_state(convulsionsState);

        Integer familyhistoryId = recordInfoByUserId.getFamilyhistoryId();
        FamilyHistory familyHistory = familyHistoryMapper.selectByPrimaryKey(familyhistoryId);
        Integer inheritanceState = familyHistory.getInheritanceState();
        recordInfoParams.setInheritance_state(inheritanceState);
        if(inheritanceState==1){
            List<Inheritance> inheritances = inheritanceMapper.selectListByFimilyHis(familyhistoryId);
            recordInfoParams.setInheritances(inheritances);
        }
        Integer marryState = familyHistory.getMarryState();
        recordInfoParams.setMarry_state(marryState);
        Integer birthState = familyHistory.getBirthState();
        recordInfoParams.setBirth_state(birthState);
        return recordInfoParams;
    }

    @Override
    public PatientInfo patientInfoById(Integer patientId) {
        PatientInfo map = patientMapper.patientInfoByLoginId(patientId);
        return map;
    }

    @Override
    public boolean editPatientById(EditPatientParams patientDoctor) {
        Integer userId = patientDoctor.getUserId();
        int i=0;
        if(userId!=null){
            Patient patient = patientMapper.selectByLoginId(userId);
            String patientNick = patientDoctor.getPatientNick();
            if(patientNick!=null){
                patient.setPatientNick(patientNick);
            }
            Integer patientSex = patientDoctor.getPatientSex();
            if(patientSex!=null){
                patient.setPatientSex(patientSex);
            }
            Date patientBirthday = patientDoctor.getPatientBirthday();
            if(patientBirthday!=null){
                patient.setPatientBirthday(patientBirthday);
            }
            Integer illage = patientDoctor.getIllage();
            if(illage!=null){
                patient.setIllage(illage);
            }
            Integer province = patientDoctor.getProvince();
            if(province!=null){
                patient.setProvince(province);
            }
            Integer city = patientDoctor.getCity();
            if(city!=null){
                patient.setCity(city);
            }
            i = patientMapper.updateByPrimaryKeySelective(patient);
        }
        return i==1;
    }
}
